from django.db import transaction
from rest_framework.views import APIView
from rest_framework_jwt.views import JSONWebTokenAPIView

from apps.system.models import Upload
from utils import response_ok, response_error
from utils.permission import IsMemberUser
from .serializers import MemberMobileSignSerializer, WeChatBindUserInfoSerializer, WeChatCode2sessionSerializer, \
    MemberInfoSerializer, MemberInfoSerializer


class UserInfoView(APIView):
    permission_classes = [IsMemberUser, ]

    def get(self, request):
        return response_ok(MemberInfoSerializer(self.request.user.member).data)


class MemberLoginView(APIView):
    # 验证码注册登录
    serializer_class = MemberMobileSignSerializer

    def post(self, request, *args, **kwargs):
        """验证码注册登录"""
        with transaction.atomic():
            ser = self.serializer_class(data=request.data)
            if ser.is_valid():
                return response_ok(ser.validated_data)
            return response_error('手机号或者验证码错误！')


class WeChatCode2sessionView(APIView):
    serializer_class = WeChatCode2sessionSerializer

    def post(self, request, *args, **kwargs):
        try:
            ser = self.serializer_class(data=request.data)
            if ser.is_valid():
                return response_ok(ser.validated_data)
            else:
                return response_error('参数错误')
        except Exception as e:
            import traceback
            traceback.print_exc()
            return response_error(str(e))


class WeChatBindPhoneNumberView(APIView):
    permission_classes = [IsMemberUser, ]
    serializer_class = WeChatBindUserInfoSerializer

    def post(self, request, *args, **kwargs):

        ser = self.serializer_class(data=request.data, context={'request': request})
        if ser.is_valid():
            return response_ok(ser.validated_data)
        else:
            return response_error('参数错误')


class WeChatUpdateUserInfoView(APIView):
    permission_classes = [IsMemberUser, ]

    def post(self, request, *args, **kwargs):
        try:
            # encryptedData = request.POST.get('encryptedData')
            # iv = request.POST.get('iv')
            # decrypted = WeChatApplet().decrypt(encryptedData, iv, self.request.user.member.session_key)
            user = self.request.user
            with transaction.atomic():
                user.nickname = request.data.get('nickName')
                user.save()

                member = self.request.user.member
                member.gender = request.data.get('gender')
                member.city = request.data.get('city')
                member.province = request.data.get('province')
                member.face_url = request.data.get('avatarUrl')
                member.save()
                member_info = MemberInfoSerializer(member).data
        except Exception as e:
            return response_error(str(e))
        return response_ok(member_info)


class UploadImageview(APIView):
    permission_classes = [IsMemberUser, ]

    def post(self, request, *args, **kwargs):
        path = request.data['path']
        file = self.request.FILES.get('file')
        upload = Upload.objects.upload(file, path, self.request.user)
        if upload:
            return response_ok({
                'id': upload.id,
                'url': upload.get_url()
            })
        return response_error('上传失败，请重新上传！')
